package com.wang.head.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.wang.common.controller.BaseController;
import com.wang.common.pojo.ApiResponse;
import com.wang.common.pojo.ApiResponseEnum;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.util.PageInfoUtil;
import com.wang.users.pojo.AUsers;
import com.wang.users.service.IUsersDbService;

/**
 * 用户的前台controller
 * @author MyJjh
 *
 */
@Controller
@RequestMapping("/head/users")
public class UsersHeadController extends BaseController
{

	@Autowired
	private IUsersDbService usersDbService;
	
	/**
	 * 退出页面
	 * 
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--logout--");
		HttpSession session = request.getSession() ;
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		try
		{
			/* 做一些清除的操作 */
			session.removeAttribute("users");
			session.removeAttribute("lastLoginTime");
			apiResponse.setCode(ApiResponseEnum.INFO_LOGOUT.getStatus());
		} catch (Exception e)
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 提示信息 */
		session.setAttribute("response", apiResponse.toJSON());
		/* 客户端跳转到登陆页面 */
		return "redirect:/login"; 
	}
	
	/**
	 * 用户列表页面
	 * @return
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--main--");
		return "/head/users/main";
	}

	/**
	 * 用户列表页面
	 * @return
	 */
	@RequestMapping("/usersList")
	public String usersList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersList--");
		ApiResponse<AUsers> response = new ApiResponse<AUsers>();
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		response = this.usersDbService.findCondListUsersService(pageInfoUtil, condMap);
		response.clearInfo();
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/head/users/usersList";
	}
	
	/**
	 * 打开用户更新页面
	 * @return
	 */
	@RequestMapping("/usersUpdate")
	public String usersUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersUpdate--");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		String id = users.getId() + ""; 
		
		condMap.clear();
		condMap.put("id", id);
		ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		users = apiResponse.getDataOneJava() ; 
		model.addAttribute("usersResponse", apiResponse.toJSON());
		
		String operType = request.getParameter("operType");
		request.setAttribute("operType", operType);
		if("updateInfo".equalsIgnoreCase(operType))
		{
			/* 根据不同的请求跳转不同的页面 */
			return "/head/users/usersUpdateInfo";
		}else if("updatePhoto".equalsIgnoreCase(operType))
		{
			/* 根据不同的请求跳转不同的页面 */
			return "/head/users/usersUpdatePhoto";
		}else if ("updatePass".equalsIgnoreCase(operType))
		{
			return "/head/users/usersUpdatePass";
		}
		return "/head/users/usersInfo";
	}
	
	/**
	 * 打开用户更新页面
	 * @return
	 */
	@RequestMapping("/usersUpdateSubmit")
	public String usersUpdateSubmit(HttpServletRequest request,Model model,MultipartFile file)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersUpdateSubmit--");
		HttpSession session = request.getSession() ; 
		ApiResponse dbResponse = new ApiResponse<>();
		/* 从session中获取信息 */
		AUsers usersSess = (AUsers) this.findObjfromSession(request, "users");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersSess.getId() + "");
		ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		AUsers users = apiResponse.getDataOneJava() ; 
		model.addAttribute("response", apiResponse.toJSON());
		
		boolean flag = false ; 
		String operType = request.getParameter("operType");
		if ("updateInfo".equalsIgnoreCase(operType))
		{
			/* 接收参数 */
			String email = request.getParameter("email");
			String trueName = request.getParameter("trueName");
			String phone = request.getParameter("phone");
			String qq = request.getParameter("qq");
			String idnumber = request.getParameter("idnumber");
			String birthdayStr = request.getParameter("birthdayStr");
			String grade = request.getParameter("grade");
			String numb = request.getParameter("numb");
			String age = request.getParameter("age");
			String sex = request.getParameter("sex");
			String headportrait = request.getParameter("headportrait");
			
			users.setTrueName(trueName);
			users.setEmail(email);
			users.setPhone(phone);
			users.setQq(qq);
			users.setIdnumber(idnumber);
			users.setBirthday(dateFormatUtil.strDate(birthdayStr));
			users.setGrade(Integer.valueOf(grade));
			users.setNumb(numb);
			users.setAge(Integer.valueOf(age));
			users.setSex(Byte.valueOf(sex));
			users.setHeadportrait(headportrait);
			
			flag = true;
		} else if ("updatePass".equalsIgnoreCase(operType))
		{
			/* 更新密码 */
			String password = request.getParameter("password");
			String souPass = request.getParameter("souPass");
			if (this.encryptUtil.checkStr(souPass, users.getPassword()))
			{
				/* 原密码正确 */
				users.setPassword(this.encryptUtil.encodeStr(password));
				flag = true;
			} else
			{
				/* 原密码不正确 */
				dbResponse.setCode(ApiResponseEnum.INFO_SOUPASS_INCORRECT.getStatus());
			}
		} else if ("resetPass".equalsIgnoreCase(operType))
		{
			String password = request.getParameter("password");
			/* 重置密码 */
			users.setPassword(this.encryptUtil.encodeStr(password));
			flag = true;
		}else if("updatePhoto".equalsIgnoreCase(operType))
		{
			/* 上传头像 */
			try
			{
				/* 更新标志 */
				if(request instanceof MultipartRequest)
				{ 
					MultipartRequest multipartRequest = (MultipartRequest) request ;
					MultipartFile multipartFile = multipartRequest.getFile("file");
					condMap.put("fileName", multipartFile.getOriginalFilename());
					condMap.put("inputStream", multipartFile.getInputStream());
					users.setUpdateTime(new Date());
					dbResponse = this.usersDbService.updateOneUsersService(users,condMap);
					model.addAttribute("response", dbResponse.toJSON());
					request.getSession().setAttribute("users", users);
				}
			} catch (Exception e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("更新图片失败了;" , e );
			}
		}
		if(flag)
		{
			dbResponse = this.usersDbService.updateOneUsersService(users);
			session.setAttribute("users", users);
		}
		dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 存储结果 */
		model.addAttribute("response", dbResponse.toJSON());
		return this.usersUpdate(request, model);
	}
}
